package com.tansun.easycare.rule.datamodel.web;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tansun.easycare.rule.refemodel.entity.RuleReleModel;
import com.tansun.easycare.rule.refemodel.service.RuleReleModelService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.tansun.easycare.core.utils.ResponseTable;
import com.tansun.easycare.rule.codeblock.entity.RuleCodeblock;
import com.tansun.easycare.rule.codeblock.service.RuleCodeblockService;
import com.tansun.easycare.rule.common.Constant;
import com.tansun.easycare.rule.common.DataCache;
import com.tansun.easycare.rule.common.ResMessage;
import com.tansun.easycare.rule.common.RuleBaseController;
import com.tansun.easycare.rule.common.SelBean;
import com.tansun.easycare.rule.common.model.Domain;
import com.tansun.easycare.rule.common.model.Item;
import com.tansun.easycare.rule.common.model.ResponseVO;
import com.tansun.easycare.rule.common.service.DataBomService;
import com.tansun.easycare.rule.datamodel.dao.RuleDataDomainDao;
import com.tansun.easycare.rule.datamodel.entity.RuleDataDomain;
import com.tansun.easycare.rule.datamodel.entity.RuleDataparams;
import com.tansun.easycare.rule.datamodel.entity.RuleDataset;
import com.tansun.easycare.rule.datamodel.model.ParamDomainVo;
import com.tansun.easycare.rule.datamodel.model.funcParamDetailsVO;
import com.tansun.easycare.rule.datamodel.service.DataModelService;
import com.tansun.easycare.rule.datamodel.service.RuleDataparamsService;
import com.tansun.easycare.rule.exception.BizException;
import com.tansun.easycare.rule.referencedata.dao.RuleReferenceDataDao;
import com.tansun.easycare.rule.referencedata.entity.RuleReferenceData;
import com.tansun.easycare.rule.utils.PageUtils;
import com.tansun.rule.utils.StringUtils;


/**
 * 数据集变量Controller
 *
 * @author lxs
 * @version 2017-02-17
 */
@RestController
@RequestMapping(value = "/ruleProj/dataModel/attribute")
public class RuleDataparamsController extends RuleBaseController {

    @Autowired
    private RuleDataparamsService ruleDataparamsService;

    @Autowired
    private DataModelService dataModelService;

    @Autowired
    private RuleDataDomainDao ruleDataDomainDao;

    @Autowired
    private RuleReferenceDataDao ruleReferenceDataDao;
    @Autowired
    private RuleReleModelService ruleReleModelService;
    
    @RequestMapping(value="moveAttribute",produces = "application/json; charset=utf-8")
    public ResponseVO moveAttribute(@RequestBody Map<String,Object> map) throws Exception {
        ResponseVO responseVO = new ResponseVO();
        String sourceId = (String)map.get("sourceId");
        String targetId = (String)map.get("targetId");
        String attrName = (String)map.get("attrName");
        String projectCode = (String)map.get("projectcode");
        if(StringUtils.isBlank(sourceId)||StringUtils.isBlank(targetId)||StringUtils.isBlank(attrName)||StringUtils.isBlank(projectCode)){
            responseVO.setDescription("移动失败，请稍候重试！");;
            responseVO.setStatus(ResponseVO.ERROR);
            return responseVO;
        }
        try {
            this.ruleDataparamsService.moveAttribute(sourceId,targetId,attrName,projectCode);
        } catch (Exception e) {
            e.printStackTrace();
            responseVO.setDescription("移动失败，请稍候重试！");;
            responseVO.setStatus(ResponseVO.ERROR);
            return responseVO;
        }
        DataCache.paramChange(projectCode);
        responseVO.setDescription("移动成功！");;
        return responseVO;
    }

    // ========================================以上为vue使用到的方法=========================================

    /**
     * 根据数据集id获取到对应的变量
     * @param ruleDataparams
     * @return
     * @throws Exception
     */
    @RequestMapping("list")
    public ResponseTable<RuleDataparams> index(@RequestBody RuleDataparams ruleDataparams) throws Exception {
        ResponseTable<RuleDataparams> rst = new ResponseTable<>();
        if(StringUtils.isEmpty(ruleDataparams.getDatasetId())){
            return  rst;
        }
        PageInfo<RuleDataparams>   pageInfo = this.ruleDataparamsService.findPage(ruleDataparams.getPage(), ruleDataparams);
       rst.setPageInfo(pageInfo);
        return rst;
    }
    @RequestMapping("delete")
    public ResponseVO delect(@RequestBody RuleDataparams ruleDataparams){
        ResponseVO responseVO = new ResponseVO();
        responseVO.setDescription("删除成功！");
        responseVO.setStatus(ResponseVO.OK);
        try {
        	String id = ruleDataparams.getId();
        	RuleDataparams rdp = this.ruleDataparamsService.get(id);
            RuleReferenceData referenceData = new RuleReferenceData();
            referenceData.setProjectCode(rdp.getProjectcode());
            referenceData.setClassName(rdp.getClassName());
            referenceData.setNameen(rdp.getName());
            List<RuleReferenceData> list = this.ruleReferenceDataDao.findPublishRuleReferenceList(referenceData);
            //是否有被决策树引用
            List<RuleReleModel> releModelLists = this.ruleReleModelService.findReleModelListForDel(rdp.getProjectcode(), id);
            List<RuleReferenceData> joinList = new ArrayList<>();
            if(!list.isEmpty() || !releModelLists.isEmpty()) {
                if(!list.isEmpty()){
                    list.forEach(item->{item.setClassName(item.getRefName()+item.getVersion());});
                    joinList.addAll(list);
                }
            	if(!releModelLists.isEmpty()){
                    releModelLists.forEach(item->{
                        RuleReferenceData ruleReferenceData = new RuleReferenceData();
                        referenceData.setClassName(item.getName());
                        referenceData.setVersion(item.getVersion());
                        joinList.add(ruleReferenceData);
                    });
                }
            	String refData = StringUtils.join(joinList.stream().map(RuleReferenceData::getClassName).collect(Collectors.toList()),";");
                responseVO.setDescription("删除失败,原因：数据模型变量被引用无法删除! { "+refData+" }");;
                responseVO.setStatus(ResponseVO.ERROR);
            }else {
            	this.ruleDataparamsService.deleteRuleDataparamsById(id);
            }
        } catch (BizException e) {
            logger.error(ExceptionUtils.getStackTrace(e));
            responseVO.setDescription("删除失败,原因："+e.getMessage());;
            responseVO.setStatus(ResponseVO.ERROR);
        }
        return  responseVO;
    }

    /**
     * 保存修改
     *
     * @param attr        变量信息模型
     * @param request     domainJsonStr：离散信息
     * @return 是否保存成功的json串
     */
    @RequestMapping(value="save",produces = "application/json; charset=utf-8")
    @ResponseBody
    public ResponseVO save(@RequestBody RuleDataparams attr, HttpServletRequest request) throws Exception {
        ResponseVO responseVO = new ResponseVO();
        String type = attr.getType();
        if (Constant.DATAMODEL_ATTRIBUTE_TYPE_ENUM.equals(type)) {//如果是码表  类型切换为string
            attr.setType(Constant.DATAMODEL_ATTRIBUTE_TYPE_STRING);
        }else if (!Constant.DATAMODEL_ATTRIBUTE_TYPE_DATE.equals(type)) {
            attr.setPattern("");
        }
        try {
            String projectCode = attr.getProjectcode();
            attr.setProjectcode(projectCode);
            List<Item> domainDataStr = attr.getDomainJsonStr();
            
            if (domainDataStr != null && !domainDataStr.isEmpty()) {
                if (StringUtils.isEmpty(attr.getDomain())) {
                    attr.setDomain(attr.getId());
                }
                this.ruleDataparamsService.saveParamsAndDomain(attr, domainDataStr);
            } else {
                this.ruleDataparamsService.saveAndUpdateRef(attr);
            }
            DataCache.paramChange(projectCode);
            responseVO.setDescription("修改成功");
            responseVO.setStatus(ResponseVO.OK);
        } catch (BizException e) {
            responseVO.setDescription(e.getMessage());;
            responseVO.setStatus(ResponseVO.ERROR);
        } catch (Exception e) {
            e.printStackTrace();
            responseVO.setDescription("保存失败");
            responseVO.setStatus(ResponseVO.ERROR);
        }
        return responseVO;
    }


    //===============以上为变量vue所用到的方法=========================
    
    @Autowired
    RuleCodeblockService ruleCodeblockService;
    /**
     *	函数变量详情页信息
     *
     * @param  funcparam
     * @return funcParamDetailsVO
     */
    @RequestMapping("funcparamedit")
    public ResponseVO addfuncparam(@RequestBody RuleDataparams funcparam) throws Exception {
       funcParamDetailsVO fpDetails =new funcParamDetailsVO();
       fpDetails.setRankRelationId(funcparam.getRankRelationId());
    	String operation ="add";
    	if(!StringUtils.isEmpty(funcparam.getId())) {
            operation = "edit";
    		RuleDataparams rulefuncparam = this.ruleDataparamsService.get(funcparam.getId());
    		fpDetails.setRulefuncparam(rulefuncparam);
    		RuleCodeblock condition = new RuleCodeblock();
    		condition.setParameterId(funcparam.getId());
    		List<RuleCodeblock> rcb = ruleCodeblockService.findList(condition);
    		if(rcb.size()>0) {
    			fpDetails.setCodeblock(rcb.get(0));
    		}
    	}
    	RuleDataset ruleDataset = this.dataModelService.get(funcparam.getDatasetId());
    	fpDetails.setIsedit(operation);
    	fpDetails.setDataset(ruleDataset);
    	ResponseVO res = new ResponseVO();
    	res.setData(fpDetails);
    	return res;
        
    }
    @RequestMapping("funcparameditDialog")
    public String addfuncparamDialog(String ruleModel,ModelMap map) throws Exception {
        String[] split = ruleModel.split("_", 2);
        RuleDataset dataCondition = new RuleDataset();
        dataCondition.setProjectcode(this.getCurrProjectCode());
        dataCondition.setName(split[0]);
        List<RuleDataset> ruleDatasetList = this.dataModelService.findList(dataCondition);
        RuleDataset ruleDataset = ruleDatasetList.get(0);
        map.put("dataset", ruleDataset);
        map.put("projectCode", ruleDataset.getProjectcode());

        RuleDataparams paramsCondiction = new RuleDataparams();
        String ruleProject = this.getCurrProjectCode();
        paramsCondiction.setProjectcode(ruleProject);
        paramsCondiction.setName(split[1]);
        paramsCondiction.setDatasetId(ruleDataset.getId());
        List<RuleDataparams> ruleDataparamsList = this.ruleDataparamsService.findList(paramsCondiction);
        RuleDataparams ruleDataparam= ruleDataparamsList.get(0);
        map.put("rulefuncparam", ruleDataparam);
        RuleCodeblock condition = new RuleCodeblock();
        condition.setParameterId(ruleDataparam.getId());
        List<RuleCodeblock> rcb = ruleCodeblockService.findList(condition);
        if(rcb.size()>0) {
            map.put("codeblock", rcb.get(0));
        }
        return "rule/datamodel/attribute/funcparameditDialog";
    }
    
    /**
     *	保存函数变量
     *
     * @param  rulefuncparam
     * @return 保存结果
     */
    @RequestMapping("funcparamsave")
    public @ResponseBody ResponseVO funcparamsave(@RequestBody RuleDataparams rulefuncparam) throws Exception {
    	ResponseVO res = new ResponseVO();
    	try {
    		this.ruleDataparamsService.saveFuncParam(rulefuncparam); 		
    		DataCache.funcParamChange(rulefuncparam.getProjectcode());

    	}catch (Exception e) {
    		e.printStackTrace();
    		res.setStatus(ResponseVO.ERROR);
    		res.setDescription(e.getMessage());
			// TODO: handle exception
		}
        return res;
    }
    
    /**
     *	编译
     *
     * @param  rulefuncparam
     * @return 编辑结果
     */    
    @RequestMapping("funcparamvalidate")
    public @ResponseBody ResponseVO funcparamvalidate(@RequestBody RuleDataparams rulefuncparam) throws Exception {
    	ResponseVO rev = new ResponseVO();
    	try {
    		RuleDataset ruleDataset = null;
        	if(!StringUtils.isEmpty(rulefuncparam.getId())) {
        		RuleDataparams tmp = this.ruleDataparamsService.get(rulefuncparam.getId());
        		ruleDataset = this.dataModelService.get(tmp.getDatasetId());
        	}else {
        		ruleDataset = this.dataModelService.get(rulefuncparam.getDatasetId());
        	}
        	rev = this.ruleDataparamsService.validate(rulefuncparam, ruleDataset.getName()+"_"+rulefuncparam.getName(),new RuleCodeblock());
        	
    	}catch (Exception e) {
    		e.printStackTrace();
    		rev.setStatus(ResponseVO.ERROR);
    		rev.setDescription(e.getMessage());
			// TODO: handle exception
		}
        return rev;
    }
    
//    @RequestMapping("funcparamsearch")
//    public @ResponseBody ResponseVO funcparamsearch(@RequestBody RuleDataparams funcparam) throws Exception {
//    	funcParamDetailsVO fpDetails =new funcParamDetailsVO();
//    	RuleDataparams rulefuncparam = this.ruleDataparamsService.get(funcparam.getId());
//        RuleCodeblock condition = new RuleCodeblock();
//        condition.setParameterId(funcparam.getId());
//        List<RuleCodeblock> rcb = ruleCodeblockService.findList(condition);
//        fpDetails.setRulefuncparam(rulefuncparam);
//        if(rcb.size()>0) {
//        	fpDetails.setCodeblock(rcb.get(0));
//        }
//        RuleDataset ruleDataset = this.dataModelService.get(funcparam.getId());
//        fpDetails.setDataset(ruleDataset);
//        ResponseVO res = new ResponseVO();
//    	res.setData(fpDetails);
//    	return res;
//    }

    @RequestMapping("isHaveEffect")
    @ResponseBody
    public ResponseVO isHaveEffect(@RequestBody RuleDataparams funcparam){
    	ResponseVO res = new ResponseVO();
    	res.setStatus(ResponseVO.ERROR);
    	res.setDescription("暂无生效版本！");
       
        RuleCodeblock condition = new RuleCodeblock();
        condition.setParameterId(funcparam.getId());
        List<RuleCodeblock> rcb = ruleCodeblockService.findList(condition);
        if(rcb.size()>0){
            RuleCodeblock ruleCodeblock = rcb.get(0);
            String activeStatus = ruleCodeblock.getActiveStatus();
            if(!"1".equals(activeStatus)){
                res.setStatus(200);
                res.setDescription("查询成功！");
            }
        }
        return res;
    }
    
    //===============以上为函数变量vue所用到的方法=========================  
    
    @RequestMapping("getRuleDataParam")
    public @ResponseBody
    ResponseVO getRuleDataParam(String id) {
        ResponseVO responseVO = new ResponseVO();
        responseVO.setStatus(200);
        try {
            responseVO.setData(this.ruleDataparamsService.get(id));
        } catch (Exception e) {
            responseVO.setStatus(400);
        }
        return responseVO;
    }

    /**
     * 获取所有变量
     *
     * @param modelName 数据模型编码（固定取dataModel）
     * @return 变量列表json值
     */

    @RequestMapping(value="getJsonArray",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getJsonArray(String modelName) throws Exception {

        ResMessage msg = null;
        List<RuleDataparams> list;
        try {
            String projectCode = getCurrProjectCode();
            RuleDataparams ruleDataparams = new RuleDataparams();
            ruleDataparams.setProjectcode(projectCode);
            ruleDataparams.setDatasetId(modelName);
            list = this.ruleDataparamsService.findList(ruleDataparams);

        } catch (Exception e) {
            logger.debug(ExceptionUtils.getStackTrace(e));

            msg = new ResMessage("failure", "获取数据失败");
            return JSONArray.toJSONString(msg);
        }
        return JSONArray.toJSONString(list);
    }

    /**
     * 根据domainType 获得数据类型
     *
     * @param request   domainType：数据类型取值类型
     * @param modelName 数据模型编码（固定取dataModel）
     * @return 数据类型列表
     */
    @RequestMapping(value="getType",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getType(HttpServletRequest request, HttpServletResponse response, String projectCode, String modelName, String pname) throws Exception {
        List<SelBean> list = new ArrayList<SelBean>();
        String domainType = request.getParameter("domainType");
        if (Constant.DATAMODEL_ATTRIBUTE_DOMAINTYPE_LINE.equals(domainType)) {
            list.add(new SelBean("(Boolean)布尔", Constant.DATAMODEL_ATTRIBUTE_TYPE_BOOLEAN));
            list.add(new SelBean("(Date)日期", Constant.DATAMODEL_ATTRIBUTE_TYPE_DATE));
            list.add(new SelBean("(Double)实型", Constant.DATAMODEL_ATTRIBUTE_TYPE_DOUBLE));
            list.add(new SelBean("(Long)整型", Constant.DATAMODEL_ATTRIBUTE_TYPE_LONG));
            list.add(new SelBean("(String)字符", Constant.DATAMODEL_ATTRIBUTE_TYPE_STRING));
            list.add(new SelBean("(Enum)枚举", Constant.DATAMODEL_ATTRIBUTE_TYPE_ENUM));
            //	list.add(new SelBean("Integer",Constant.DATAMODEL_ATTRIBUTE_TYPE_INTEGER));
        } else if (Constant.DATAMODEL_ATTRIBUTE_DOMAINTYPE_COLLECTION.equals(domainType)) {
            try {
                projectCode = getCurrProjectCode();
                List<RuleDataset> dmList = this.dataModelService.getDataModelListByProjectCode(projectCode, null);
                for (RuleDataset dm : dmList) {
                    if (dm.getName().equals(pname)) continue;
                    list.add(new SelBean(dm.getName() + "(" + dm.getChzn() + ")", dm.getName()));
                }
            } catch (Exception e) {
                logger.debug(ExceptionUtils.getStackTrace(e));
            }
            //2015年11月26日 11:08:15  万业要求增加
            list.add(new SelBean("(Date)日期", Constant.DATAMODEL_ATTRIBUTE_TYPE_DATE));
            list.add(new SelBean("(Double)实型", Constant.DATAMODEL_ATTRIBUTE_TYPE_DOUBLE));
            list.add(new SelBean("(Long)整型", Constant.DATAMODEL_ATTRIBUTE_TYPE_LONG));
            list.add(new SelBean("(String)字符", Constant.DATAMODEL_ATTRIBUTE_TYPE_STRING));
            list.add(new SelBean("(Boolean)布尔", Constant.DATAMODEL_ATTRIBUTE_TYPE_BOOLEAN));
            list.add(new SelBean("(Enum)枚举", Constant.DATAMODEL_ATTRIBUTE_TYPE_ENUM));
            //list.add(new SelBean("Integer",Constant.DATAMODEL_ATTRIBUTE_TYPE_INTEGER));
        } else if (Constant.DATAMODEL_ATTRIBUTE_DOMAINTYPE_SEPARATE.equals(domainType)) {
            list.add(new SelBean("Date", Constant.DATAMODEL_ATTRIBUTE_TYPE_DATE));
            list.add(new SelBean("Double", Constant.DATAMODEL_ATTRIBUTE_TYPE_DOUBLE));
            list.add(new SelBean("Long", Constant.DATAMODEL_ATTRIBUTE_TYPE_LONG));
            list.add(new SelBean("String", Constant.DATAMODEL_ATTRIBUTE_TYPE_STRING));
            list.add(new SelBean("Emun", Constant.DATAMODEL_ATTRIBUTE_TYPE_ENUM));
            //	list.add(new SelBean("Integer",Constant.DATAMODEL_ATTRIBUTE_TYPE_INTEGER));
            list.add(new SelBean("Boolean", Constant.DATAMODEL_ATTRIBUTE_TYPE_BOOLEAN));
        } else if (Constant.DATAMODEL_ATTRIBUTE_DOMAINTYPE_DERIVES.equals(domainType)) {
            list.add(new SelBean("Boolean", Constant.DATAMODEL_ATTRIBUTE_TYPE_BOOLEAN));
            list.add(new SelBean("Date", Constant.DATAMODEL_ATTRIBUTE_TYPE_DATE));
            list.add(new SelBean("Double", Constant.DATAMODEL_ATTRIBUTE_TYPE_DOUBLE));
            list.add(new SelBean("Long", Constant.DATAMODEL_ATTRIBUTE_TYPE_LONG));
            list.add(new SelBean("String", Constant.DATAMODEL_ATTRIBUTE_TYPE_STRING));
            //	list.add(new SelBean("Integer",Constant.DATAMODEL_ATTRIBUTE_TYPE_INTEGER));
        }
        return JSONArray.toJSONString(list);
    }

    /**
     * 获得范围类型
     *
     * @return 返回类型列表
     */
    @RequestMapping("getDomainType")
    @ResponseBody
    public String getDomainType() throws Exception {
        List<SelBean> list = new ArrayList<SelBean>();
        list.add(new SelBean("连续型", Constant.DATAMODEL_ATTRIBUTE_DOMAINTYPE_LINE));
        list.add(new SelBean("集合型", Constant.DATAMODEL_ATTRIBUTE_DOMAINTYPE_COLLECTION));
        list.add(new SelBean("离散型", Constant.DATAMODEL_ATTRIBUTE_DOMAINTYPE_SEPARATE));
        list.add(new SelBean("衍生型", Constant.DATAMODEL_ATTRIBUTE_DOMAINTYPE_DERIVES));
        return JSONArray.toJSONString(list);
    }



    /**
     * 获取数据集及数据集对应的变量
     *
     * @return 返回数据集及数据集变量的json
     */
    @RequestMapping(value="getDmJson",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getDmJson() throws Exception {
        List<SelBean> list = new ArrayList<SelBean>();
        try {
            String projectCode = getCurrProjectCode();
            //String path=RuleProject.HOMEPATH+"/"+projectCode+"/"+modelName+Constant.DMFILE;
            List<RuleDataset> iList = this.dataModelService.getDataModelListByProjectCode(projectCode, null);

            if (iList == null) return JSONArray.toJSONString(list);
            List<RuleDataparams> dpList = null;
            for (RuleDataset d : iList) {
                List<SelBean> alist = new ArrayList<SelBean>();
                RuleDataparams ruleDataparams = new RuleDataparams();
                ruleDataparams.setDatasetId(d.getId());
                dpList = this.ruleDataparamsService.findList(ruleDataparams);
                if (dpList != null) {
                    for (RuleDataparams a : dpList) {
                        alist.add(new SelBean(a.getChzn(), "#{" + a.getId() + "}", a.getType()));
                    }
                }
                list.add(new SelBean(d.getChzn(), d.getName(), alist));
            }
        } catch (Exception e) {
            FileUtils.write(new File("E:/exception.txt"), ExceptionUtils.getStackTrace(e));
            logger.debug(ExceptionUtils.getStackTrace(e));
        }
        return JSONArray.toJSONString(list);
    }

    //getAttrJson

    /**
     * 获得变量选择模式  value = #{attrid}
     *
     * @return 变量json字符串
     */
    @RequestMapping(value="getAttrJson",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getAttrJson(HttpServletRequest request, String isNeedDerives) throws Exception {
        List<SelBean> list = new ArrayList<SelBean>();
        String pname = request.getParameter("pname");
        if (pname == null) return JSONArray.toJSONString(list);
        try {
            //String 	projectCode=getCurrProjectCode();
            Map<String, Object> map = new HashMap();
            map.put("projectcode", this.getCurrProjectCode());
            map.put("className", pname);

            //ruleDataparams.setDatasetId(datasetId);
            List<RuleDataparams> iList = this.ruleDataparamsService.findRuleDataparamsByMap(map);
            if (iList == null) return JSONArray.toJSONString(list);
            for (RuleDataparams a : iList) {
                if ("true".equals(a.getIsDerives()) && !"1".equals(isNeedDerives)) continue;//排除衍生变量
                list.add(new SelBean(a.getChzn(), "#{" + a.getId() + "}", a.getType(), a.getCollection()));
            }


        } catch (Exception e) {
            logger.debug(ExceptionUtils.getStackTrace(e));
        }
        return JSONArray.toJSONString(list);
    }

    /**
     * 验证变量英文名是否存在
     *
     * @param key         对比英文名
     * @param pname       数据集
     * @param initValue   空值
     * @return 操作是否成功的json串
     */
    @RequestMapping(value="nameUniqueCheck")
    @ResponseBody
    public ResponseVO nameUniqueCheck(@RequestBody RuleDataparams ruleparams) throws Exception {
    	ResponseVO rev = new ResponseVO();
    	rev.setStatus(ResponseVO.OK);
    	rev.setData(true);
    	String datasetId = ruleparams.getDatasetId();
    	String name = ruleparams.getName();
    	String chzn = ruleparams.getChzn();
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(chzn)) {
        	rev.setData(false);
        	rev.setDescription("参数有误，服务器未接收到关键字");
            return rev;
        }
        boolean isNew = StringUtils.isEmpty(ruleparams.getId());
        
        RuleDataparams ruleDataparams = new RuleDataparams();
        ruleDataparams.setProjectcode(ruleparams.getProjectcode());
        ruleDataparams.setDatasetId(datasetId);
        ruleDataparams.setName(name);
        List<RuleDataparams> namelist = this.ruleDataparamsService.findList(ruleDataparams);
        
        ruleDataparams.setName(null);
        ruleDataparams.setChzn(chzn);
        List<RuleDataparams> chznlist = this.ruleDataparamsService.findChznList(ruleDataparams);
        if (namelist != null && ((isNew && !namelist.isEmpty() ) || (!isNew && namelist.size()>1))) {
            rev.setData(false);
            rev.setDescription("变量名称重复，请使用其他有效名称");
        }else if(chznlist != null && ((isNew && !chznlist.isEmpty() ) || (!isNew && chznlist.size()>1))) {
            rev.setData(false);
            rev.setDescription("中文名称重复，请使用其他有效名称");
        }
        return rev;
    }
    //===============以上为数据模型变量vue所用到的方法========================= 


    /**
     * 过根据domian name  获得键值对
     *
     * @return 键值对列表json
     */
    @RequestMapping("getDomainItemByName")
    @ResponseBody
    public ResponseTable<Item> getDomainItemByName(@RequestBody RuleDataparams param,HttpServletRequest request) throws Exception {
    	PageInfo<Item> pageInfo = new PageInfo<>();
        ResponseTable<Item> resVo  = new  ResponseTable<Item>(pageInfo);
        if (param != null && StringUtils.isNotEmpty(param.getId())) {
            try {
            	List<Item> iList = new ArrayList<Item>();
                RuleDataDomain ruleDataDomain = new RuleDataDomain();
                ruleDataDomain.setDomainId(param.getId());
                List<RuleDataDomain> dList = this.ruleDataparamsService.findDataDomainList(ruleDataDomain);
                if (dList != null && !dList.isEmpty() ) {
	                Item item = null;
	                for (RuleDataDomain d : dList) {
	                    item = new Item();
	                    item.setId(d.getId());
	                    item.setName(d.getName());
	                    item.setValue(d.getDomainValue());
	                    iList.add(item);
	                }
                }
                pageInfo = PageUtils.createSimglePageInfo(iList);
                resVo  = new ResponseTable<Item>(pageInfo);
            } catch (Exception e) {
                e.printStackTrace();
                logger.debug(ExceptionUtils.getStackTrace(e));
            }
        } 

        return resVo;
    }
    //===============以上为数据模型变量vue所用到的方法========================= 
    @Autowired
    private DataBomService dataBomService;
    /**
     * 过根据domian name  获得键值对
     *
     * @return 键值对列表json
     */
    @RequestMapping("getDomainItemByParamList")
    @ResponseBody
    public ResponseVO getDomainItemByParamList(@RequestBody ParamDomainVo param,HttpServletRequest request) throws Exception {
    	ResponseVO rev = new ResponseVO();
    	rev.setStatus(ResponseVO.OK);
        List<RuleDataparams> paramList = param.getParamList();
        if (paramList != null && !paramList.isEmpty()) {
        	try {
        		// 缓存的枚举项
        	    Map<String, List<RuleDataDomain>> mapCache = dataBomService.findDomainMap();
	        	// 存储查询枚举结果
	        	Map<String,List<Item>> domainMap = new HashMap<String,List<Item>>();
	        	// 缓存中没有的枚举，需要重新查询
	        	List<String> domainIds = new ArrayList<String>();
        		List<Item> iList = null;
        		Item item = null;
	        	List<RuleDataDomain> dList = null;
	        	for(RuleDataparams ruleDataparams:paramList) {
	        		String paramId = ruleDataparams.getId();
	        		dList = mapCache.get(paramId);
	        		if(dList != null && !dList.isEmpty()) {
			            for (RuleDataDomain d : dList) {
		                	String domainId = d.getDomainId();
		                	if(domainMap.containsKey(domainId)) {
		                		iList = domainMap.get(domainId);
		                	}else {
		                		iList = new ArrayList<Item>();
		                		domainMap.put(domainId, iList);
		                	}
		                    item = new Item();
		                    item.setId(d.getId());
		                    item.setName(d.getName());
		                    item.setValue(d.getDomainValue());
		                    iList.add(item);
		                }
	        		}else {
	        			domainIds.add(paramId);
	        		}
	        	}
	        	if(!domainIds.isEmpty()) {
		        	dList = this.ruleDataparamsService.findDataDomainListByDomainIds(domainIds);
		        	if(dList!=null && !dList.isEmpty()) {
			            for (RuleDataDomain d : dList) {
		                	String domainId = d.getDomainId();
		                	if(domainMap.containsKey(domainId)) {
		                		iList = domainMap.get(domainId);
		                	}else {
		                		iList = new ArrayList<Item>();
		                		domainMap.put(domainId, iList);
		                	}
		                    item = new Item();
		                    item.setId(d.getId());
		                    item.setName(d.getName());
		                    item.setValue(d.getDomainValue());
		                    iList.add(item);
		                }
		        	}
	        	}
	            Comparator<Item> itemComparator = new Comparator<Item>() {  
	                @Override  
	                public int compare(Item o1, Item o2) {  
	                    return o1.getValue().compareTo(o2.getValue());  
	                }  
	            };
	            for(String key:domainMap.keySet()) {
	            	iList = domainMap.get(key);
	            	if(iList!=null && !iList.isEmpty()) {
	            		Collections.sort(iList,itemComparator);
	            	}
	            }
	            param.setDomainMap(domainMap);
	        	rev.setData(param);
            } catch (Exception e) {
            	String error = ExceptionUtils.getStackTrace(e);
                e.printStackTrace();
                logger.debug(error);
                rev.setDesDetail(error);
                rev.setStatus(ResponseVO.ERROR);
            }
        }
        return rev;
    }
    
    
    /**
     * 公式说明
     *
     * @return 页面路径
     */
    @RequestMapping("mathDesc")
    public String mathDesc() {
        return "rule/datamodel/attribute/mathDesc";
    }

    /**
     * 删除变量
     * @param ids id
     */
    @RequestMapping(value="delect",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String delect(@RequestParam("ids[]") String[] ids) throws Exception {
        ResMessage msg;
        if (ids == null) {
            msg = new ResMessage("failure", "删除失败，参数有误");
            return JSONArray.toJSONString(msg);
        }
        boolean success;
        try {
            for (String id : ids) {
                this.ruleDataparamsService.deleteRuleDataparamsById(id);
            }
            success = true;
        } catch (Exception e) {
        	msg = new ResMessage("failure", "删除失败,原因："+e.getMessage());
            logger.debug(ExceptionUtils.getStackTrace(e));
            //msg = new ResMessage("failure", "删除失败，读写文件出错或者会话过期，尝试刷新");
            return JSONArray.toJSONString(msg);
        }
        if (!success) {
            msg = new ResMessage("failure", "删除失败，没有找到对应数据");
            return JSONArray.toJSONString(msg);
        }
        msg = new ResMessage("success", "删除成功");
        return JSONArray.toJSONString(msg);
    }


    /**
     * 获取变量的离散值信息
     *
     * @param attrId 变量id
     */
    @RequestMapping("transferDomainKey")
    @ResponseBody
    public String transferDomainKey(String name, String attrId) throws Exception {
        if (name == null) return null;
        if (attrId == null) return null;
        RuleDataDomain dataDomain = new RuleDataDomain();
        dataDomain.setDomainId(attrId);
        dataDomain.setDomainValue(name);
        List<RuleDataDomain> list = this.ruleDataparamsService.findDataDomainList(dataDomain);
        if (list != null && list.size() > 0) {
            return list.get(0).getName();
        }
        return null;
    }

    /**
     * 获取可以移动的数据集列表
     *
     * @return 页面路径
     */
    @RequestMapping("moveableList")
    public String getMoveableList() {
        return "rule/datamodel/attribute/moveAttribute";
    }


}